package NC38_螺旋矩阵;

import java.util.ArrayList;

public class Solution {
    public ArrayList<Integer> spiralOrder(int[][] matrix) {
        ArrayList<Integer> res = new ArrayList<>();
        if (matrix.length == 0){
            return res;
        }
        int top = 0, bottom = matrix.length - 1;
        int left = 0, right = matrix[0].length - 1;

        while (top < (matrix.length + 1) / 2 && left < (matrix[0].length + 1) / 2){
            for (int i = left; i <= right; i++){
                res.add(matrix[top][i]);
            }

            for (int i = top + 1; i <= bottom; i++){
                res.add(matrix[i][right]);
            }

            for (int i = right - 1; i >= left & top != bottom; i--){
                res.add(matrix[bottom][i]);
            }

            for (int i = bottom - 1; i >= top + 1 && left != right; i--){
                res.add(matrix[i][left]);
            }
            top++;
            bottom--;
            left++;
            right--;
        }
        return res;
    }
}